<?php
namespace App\Controllers;

/**
 *
 */
class BaseController
{
    protected $request;
    protected $response;
    private $argv = [];

    final public function __construct($request, $response)
    {
        $this->request  = $request;
        $this->response = $response;
        $this->init();
    }

    protected function init()
    {

    }

    public function getAction()
    {
        return ['<h1>get ' . $this->request->server['request_uri'] . '</h1>', 200];
    }

    public function postAction()
    {
        return ['<h1>post ' . $this->request->server['request_uri'] . '</h1>', 201];
    }

    public function putAction()
    {
        return ['<h1>put ' . $this->request->server['request_uri'] . '</h1>', 201];
    }

    public function patchAction()
    {
        return ['<h1>patch ' . $this->request->server['request_uri'] . '</h1>', 201];
    }

    public function deleteAction()
    {
        return ['<h1>delete ' . $this->request->server['request_uri'] . '</h1>', 204];
    }

    protected function display($tmpl, array $argv = [])
    {
        if (!empty($argv)) {
            $this->assign($argv);
        }
        return [$this->fetch(VIEWPATH . DS . $tmpl), 200];
    }

    protected function assign($var, $value = null)
    {
        if (is_array($var)) {
            $this->argv = array_merge($this->argv, $var);
        } elseif (is_string($var)) {
            $this->argv[$var] = $value;
        }
        return $this;
    }

    protected function fetch($tmpl)
    {
        if (!is_file($tmpl)) {
            return false;
        }

        extract($this->argv, EXTR_OVERWRITE);
        ob_start();
        include $tmpl;
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }

    public function clear()
    {
        $this->argv = [];
    }
}
